import AES from "crypto-js/aes"
import ENC_UTF8 from "crypto-js/enc-utf8"
import WebStorageCache from "web-storage-cache"
import { LOCAL_ENCRYPTED_KEY } from "@/common/config"

const cache = new WebStorageCache()
const isEncrypt = true
const isEncryptPartial = true

function getCache(key) {
  const encryptValue = cache.get(key)
  if (encryptValue === null) {
    return null
  }
  const bytes = AES.decrypt(encryptValue, LOCAL_ENCRYPTED_KEY)
  const plaintext = bytes.toString(ENC_UTF8)
  return JSON.parse(plaintext)
}

function setCache(key, value) {
  const encryptValue = AES.encrypt(JSON.stringify(value), LOCAL_ENCRYPTED_KEY).toString()
  return cache.set(key, encryptValue)
}

function deleteCache(key) {
  return cache.delete(key)
}

function getCacheWrapper(key) {
  if (isEncrypt || isEncryptPartial) {
    return getCache(key)
  } else {
    return cache.get(key)
  }
}

function setCacheWrapper(key, value) {
  if (isEncrypt || isEncryptPartial) {
    return setCache(key, value)
  } else {
    return cache.set(key, value)
  }
}

export const wsCache = {
  get: getCacheWrapper,
  set: setCacheWrapper,
  delete: deleteCache
}
